<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends BaseController {
	public function index() {
		$model = new \Think\Model ();
		
		$data = $model->table ( "wpsk_hottopic h,wpsk_topic t" )->where ( "h.topic_id=t.id" )->field ( 't.*,h.id as hot_id' )->select ();
		foreach ( $data as $k => $value ) {
			$data [$k] ["count"] = M ( "comment" )->where ( "topic_id='" . $value ['id'] . "'" )->count ();
		}
		
		$hdata = M( "topic" )->order("addtime desc")->limit(6)->select ();
		foreach ( $hdata as $k => $value ) {
			$hdata [$k] ["count"] = M ( "comment" )->where ( "topic_id='" . $value ['id'] . "'" )->count ();
		}
		
		 $model=new \Think\Model;

        $qdata = $model->table("wpsk_hotquestionnaire h,wpsk_questionnaires q")->where("h.questionnaire_id=q.id")
        				->field('q.*,h.id as hot_id')->select();
	 foreach ( $qdata as $k => $value ) {
			$qdata [$k] ["count"] = M ( "reply" )->where ( "questionnaire_id='" . $value ['id'] . "'" )->count ();
		}
        
      	$this->assign("qdata",$qdata);
       
		
		$this->assign ( "info", $data );
		$this->assign ( "data", $hdata );
		$class = M ( 'topicclass' )->select ();
		$this->assign ( "class", $class );
		$this->display ();
	}
	
	public function content() {
		$model = new \Think\Model ();
		$topicid = I ( 'get.id' );
		$data = $model->table ( "wpsk_topicclass c,wpsk_topic t" )->where ( "c.id=t.class and t.id='" . $topicid . "'" )->field ( 't.*,c.name as classname' )->find ();
		
		$commentcount = M ( "comment" )->where ( "topic_id='" . $topicid . "'" )->count ();
		$comments = M ( "comment" )->where ( "topic_id='" . $topicid . "'" )->select ();
		$this->assign ( "count", $commentcount );
		$this->assign ( "comment", $comments );
		$this->assign ( "info", $data );
		$this->display ();
	
	}
	
	/**
	 * 增加评论
	 */
	public function addcomment() {
		$data ['topic_id'] = $_POST ['id'];
		$data ['value'] = $_POST ['content'];
		$data ['addtime'] = time ();
		$data ['author'] = $_SESSION ['user'] ['nickname'];
		$data ['headimg'] = $_SESSION ['user'] ['headimgurl'];
		$result = M ( "comment" )->add ( $data );
		
		$this->ajaxReturn ( $data, 'JSON' );
	
	}
	
	public function listdata() {
		$id = I ( 'get.id' );
		$data = M ( "topic" )->where ( "class='" . $id . "' and ispub=1" )->select ();
		
		foreach ( $data as $k => $value ) {
			$data [$k] ["count"] = M ( "comment" )->where ( "topic_id='" . $value ['id'] . "'" )->count ();
		}
		$title = M ( 'topicclass' )->where ( "id='" . $id . "'" )->find ();
		
		$class = M ( 'topicclass' )->select ();
		$this->assign ( "class", $class );
		$this->assign ( "topic", $data );
		$this->assign ( "title", $title );
		
		$this->display ();
	}
	
	/**
	 * 问卷列表
	 */
	public function questionnaire() {
		
		$data = M ( "questionnaires" )->where ( "ispub=1 and iswp=0" )->order ( 'create_date desc' )->select ();
		foreach ( $data as $k => $value ) {
			$data [$k] ["count"] = M ( "reply" )->where ( "questionnaire_id='" . $value ['id'] . "'" )->count ();
		}
		$qdata=M("questionnaires")->where("openid='".$_SESSION['user']['openid']."'")->select();
   		 foreach ( $qdata as $k => $value ) {
			$qdata [$k] ["count"] = M ( "reply" )->where ( "questionnaire_id='" . $value ['id'] . "'" )->count ();
		}
		
		$this->assign ( "questionnaire", $data );
		$this->assign ( "mydata", $qdata );
		$this->display ();
	}
/**
	 * 微评问卷列表
	 */
	public function equestionnaire() {
		
		$data = M ( "questionnaires" )->where ( "ispub=1 and iswp=1" )->order ( 'create_date desc' )->select ();
		foreach ( $data as $k => $value ) {
			$data [$k] ["count"] = M ( "reply" )->where ( "questionnaire_id='" . $value ['id'] . "'" )->count ();
		}
		$qdata=M("questionnaires")->where("openid='".$_SESSION['user']['openid']."'")->select();
   		 foreach ( $qdata as $k => $value ) {
			$qdata [$k] ["count"] = M ( "reply" )->where ( "questionnaire_id='" . $value ['id'] . "'" )->count ();
		}
		
		$this->assign ( "questionnaire", $data );
		$this->assign ( "mydata", $qdata );
		$this->display ();
	}
	/**
	 * 微评问卷.
	 */
	public function wpquestions(){
	$id = I ( 'get.id' );
		$ishere = M ( 'reply' )->where ( "openid='" . $_SESSION ['user'] ['openid'] . "' and questionnaire_id='" . $id . "'" )->count ();
		if ($ishere) {
			echo "<script language=\"javascript\">window.location.href='statistic.html?questionnaireID=".$id."'</script>";
		}
		else{
		$questionnaires = M ( "questionnaires" )->where ( "id='" . $id . "'" )->find ();
		$data = M ( "questions" )->where ( "questionnaire_id='" . $id . "'" )->select ();
		foreach ( $data as $k => $value ) {
			$data [$k] ['options'] = json_decode ( $value ['options'], true );
		}
		$this->assign ( "questionnaire", $questionnaires );
		$this->assign ( "info", $data );
		$this->display ();
		}
	
	}
	
	/**
	 * 问卷内容
	 */
	public function questionnaire_content() {
		$id = I ( 'get.id' );
		$ishere = M ( 'reply' )->where ( "openid='" . $_SESSION ['user'] ['openid'] . "' and questionnaire_id='" . $id . "'" )->find ();
		if ($ishere) {
			echo "<script language=\"javascript\">window.location.href='statistic.html?questionnaireID=".$id."'</script>";
		}
		else{
		$questionnaires = M ( "questionnaires" )->where ( "id='" . $id . "'" )->find ();
		$data = M ( "questions" )->where ( "questionnaire_id='" . $id . "'" )->select ();
		foreach ( $data as $k => $value ) {
			$data [$k] ['options'] = json_decode ( $value ['options'], true );
		}
		$this->assign ( "questionnaire", $questionnaires );
		$this->assign ( "info", $data );
		$this->display ();
		}
		
	}
	
	/**
	 * 回答问题
	 */
	public function addreply() {
		$questionnaireID = $_POST ['id'];
		$questionnarieType = M ( 'Questionnaires' )->getFieldById ( $questionnaireID, 'type' );
		$data = array ('questionnaire_id' => $_POST ['id'], 'reply' => $_POST ['content'] );
		
		$data = array_merge ( $data, session ( 'user' ) ); //合并上用户信息
		

		$data ['headimgurl'] = substr_replace ( $data ['headimgurl'], '46', - 1 );
		$ishere = M ( 'reply' )->where ( "openid='" . $_SESSION ['user'] ['openid'] . "' and questionnaire_id='" . $questionnaireID . "'" )->find ();
		if ($ishere) {
			$msg = array ('type'=>'2','errorMsg' => "您已经回答此问题！" );
			$this->ajaxReturn ( $msg, 'JSON' );
		} else {
			$status = M ( 'Reply' )->add ( $data );
			if ($status === false) { //入库失败
				$msg = array ('type'=>'2','errorMsg' => "问卷入库失败，详情：" + M ( 'Reply' )->getDbError () );
				
				$this->ajaxReturn ( $msg, 'JSON' );
			} else { //入库成功
				
				$coupon = M ( "coupon" )->where ( "company_id='" . $questionnarieType . "' and used=0" )->count ();
				$allcount=M ( "coupon" )->where ( "company_id='" . $questionnarieType . "' and used=0" )->count ();
				if($allcount){
				if ($coupon ) {
					$coupon = M ( "coupon" )->where ( "company_id='" . $questionnarieType . "' and used=0" )->find ();
					$coupondata ['used'] = 1;
					$coupondata ['openid'] = $data ["openid"];
					$coupondata ['nickname'] = $_SESSION["user"]["nickname"];
					$coupondata ['headimg'] =$_SESSION ['user'] ['headimgurl'];
					$result = M ( "coupon" )->where ( "id='" . $coupon ['id'] . "'" )->save ( $coupondata );
					$count = M ( "Reply" )->where ( "questionnaire_id='" . $questionnaireID . "'" )->count ();
					$count = " <br> 问卷提交人数" . $count . "人";
					if ($result) {
						$msg = array ('type'=>'2','errorMsg' => $coupon ["value"] );
					} else {
						$msg = array ('type'=>'2','errorMsg' => "优惠券已发完" );
					}
				} else {
					$msg = array ('type'=>'2','errorMsg' => "优惠券已发完" );
				}
				}
				else{
				$msg = array ('type'=>'3','errorMsg' => "谢谢您提交问卷！" );
				}
				
				$this->ajaxReturn ( $msg, 'JSON' );
			
			}
		}
	}
	/**
	 * 增加问卷
	 */
	public function addquestionnaire() {
		$data ['type'] = 0;
		$data ['create_date'] = date ( "Y-m-d", time () );
		$data ["expire_date"] = date ( "Y-m-d", time () + (365 * 24 * 60 * 60) );
		$data['name']=I("post.name");
		$data['description']=I("post.description");
		$data ["iswp"] = 0;
		$data ["ispub"] = 0;
		$data["nickname"]=$_SESSION["user"]["nickname"];
		$data["openid"]=$_SESSION["user"]["openid"];
		$id = M ( 'Questionnaires' )->add ( $data );
		if ($id === false) { //入库失败
			$msg = array ('status' => 0, 'id' => "问卷入库失败，详情：" + M ( 'Reply' )->getDbError () );
		} else
			$msg = array ('status' => 1, 'id' => $id );
		$this->ajaxReturn ( $msg, 'JSON' );
	
	}
	/**
	 * 增加话题及问卷
	 */
	public function post(){
			
			$tid = empty ( I ( "get.tid" ) )? 0 : I ( "get.tid" );
			$qid = empty ( I ( "get.qid" ) )? 0 : I ( "get.qid" );
			
			if (!($qid == 0)) {
			$questionnaires = M ( "questionnaires" )->where ( "id='" . $qid . "'" )->find ();
			$data = M ( "questions" )->where ( "questionnaire_id='" . $qid . "'" )->select ();
			$count=M ( "questions" )->where ( "questionnaire_id='" . $qid . "'" )->count ();
			$this->assign ( "questionnaire", $questionnaires );
			$this->assign ( "count", $count );
			$this->assign ( "info", $data );
			$this->assign ( "qid", $qid );
			$this->assign ( "tid", 0 );
			$this->assign ( "cid", 1 );
			}
			else if(!($tid==0)){
			$tdata=M("topic")->where("id='".$tid."'")->find();
			$this->assign ( "tinfo", $tdata );
			$this->assign ( "count", 0 );
			$this->assign ( "qid", 0 );
			$this->assign ( "tid", $tid );
			$this->assign ( "cid", 0 );
			}
			else{
			$this->assign ( "count", 0 );
			$this->assign ( "qid", 0 );
			$this->assign ( "tid", 0 );
			$this->assign ( "cid", 0 );
			}
			
			$dataclass=M("topicclass")->select();
        	$this->assign("class",$dataclass);
        	
			$this->display();
	}
	/**
	 * 问卷详情
	 */
	public function postcontent() {
		
		$id = I ( "get.id" );
		$cid = empty ( I ( "get.cid" ) )? 0 : I ( "get.cid" );
		if (!($id == 0)) {
		$data = M ( "questions" )->where ( "id='" . $cid . "'" )->find ();
		$data['options']=json_decode($data['options'],true);
		
		
		$this->assign("type",$data["options"][0]['type']);
		$this->assign ( "id", $id );
		$this->assign("count",count($data["options"]));
		$this->assign ( "info", $data );
		}
		$this->display ();
	
	}
	
	/**
	 * 根据ID增加问题
	 */
	public function addquestion() {
		$id = empty ( I ( "post.id" ) ) ? 0 : I ( "post.id" );
		if ($id == 0) {
			$data ["name"] = I ( "post.name" );
			$data ["options"] = $_POST ['options'];
			$data ["questionnaire_id"] = $_POST ['qid'];
			$data ["sort"] = M ( "questions" )->where ( "questionnaire_id='" . I ( "post.qid" ) . "'" )->count ();
			
			$status = M ( "questions" )->add ( $data );
			
			if ($status === false) {
				$msg = array ('status' => 0, 'id' => "问卷入库失败，详情：" + M ( 'questions' )->getDbError () );
			} 
			else {
				$msg = array ('status' => 1, 'id' => $status );
			
			}
			$this->ajaxReturn ( $msg, 'JSON' );
		} 
		else {
			$data ["name"] = I ( "post.name" );
			$data ["options"] = I ( "post.options" );
			
			$status = M ( "questions" )->where("id='".$id."'")->save ( $data );
			
			if ($status === false) {
				$msg = array ('status' => 0, 'id' => "问卷入库失败，详情：" + M ( 'questions' )->getDbError () );
			} 
			else {
				$msg = array ('status' => 1, 'id' => $status );
			
			}
			$this->ajaxReturn ( $msg, 'JSON' );
			
		}
	
	}
	
	/**
	 * 删除问题
	 */
	public function delquestion(){
		$id=I("post.id");
		 $questions = M('Questions');
        $state = $questions->delete($id);
        if ($state === false) {
				$msg = array ('status' => 0, 'id' => "删除失败" );
			} 
			else {
				$msg = array ('status' => 1, 'id' => $state );
			
			}
			$this->ajaxReturn ( $msg, 'JSON' );
	}

	/**
	 * 发布问卷
	 */
	public function publicquestion(){
		$data['id']=I("post.id");
		$data['name']=I("post.name");
		$data['description']=I("post.description");
		$data['ispub']=1;
		
		$state=M("questionnaires")->save($data);
		 if ($state === false) {
				$msg = array ('status' => 0, 'msg' => "发布失败" );
			} 
			else {
				$msg = array ('status' => 1, 'msg' => "发布成功" );
			
			}
			$this->ajaxReturn ( $msg, 'JSON' );
	}
	
	
 /* 话题添加 */
    public function addtopic()
    {
      $id = empty ( I ( "post.id" ) ) ? 0 : I ( "post.id" );
      if($id==0){
         	$data ["pic"] = $this->upload ( $_FILES ['pic'] );
      		$data['type']=0;
      		$data['title']=$_POST['title'];
      		$data['addtime']=time();
      		
      		$data ["ispub"] = 1;
      		$data['class']=$_POST['class'];
      		$data ['author'] = $_SESSION ['user'] ['nickname'];
			$data ['headimg'] =$_SESSION ['user'] ['headimgurl'];
      		$data['context']=$_POST['content'];
      		
      	
      		$model = M('topic');
      		$state = $model->add($data);
      		
      	 if ($state === false) {
				echo "<script language=\"javascript\">alert('保存失败！');location.href = 'javascript:history.go(-1)'</script>";
			} 
			else {
				echo "<script language=\"javascript\">alert('修改成功！');location.href = 'javascript:history.go(-1)'</script>";
			}
      		
      }
      else{
      	if ($_FILES ['pic'] ['name'] != null)
    	   $data ["pic"] = $this->upload ( $_FILES ['pic'] );
      	$data['id']=$_POST['id'];
      		$data['title']=$_POST['title'];
      		$data ["ispub"] = 1;
      		$data['class']=$_POST['class'];
      		$data ['author'] = $_SESSION ['user'] ['nickname'];
			$data ['headimg'] =$_SESSION ['user'] ['headimgurl'];
      		$data['context']=$_POST['content'];
 
      		$model = M('topic');
      		$state = $model->save($data);
      	 if ($state === false) {
				echo "<script language=\"javascript\">alert('保存失败！');location.href = 'javascript:history.go(-2)'</script>";
			} 
			else {
				echo "<script language=\"javascript\">alert('修改成功！');location.href = 'javascript:history.go(-2)'</script>";
			}
      		
      }
      		
    }
    
    /**
     * 个人资料
     */
    public function mine(){
    	$openid=$_SESSION['user']['openid'];
    	$tcount=M("topic")->where("openid='".$openid."'")->count()+M("questionnaires")->where("openid='".$openid."'")->count();
    	$rcount=M("reply")->where("openid='".$openid."'")->count();
    	$this->assign("tcount",$tcount);
    	$this->assign("rcount",$rcount);
    	$this->display();
    }
    
    /**
     * 我的发帖
     */
    public function mytopic(){
    	$id=I("get.id");
    	$openid=$_SESSION['user']['openid'];
    	$tdata=M("topic")->where("openid='".$openid."'")->select();
   		 foreach ( $tdata as $k => $value ) {
			$tdata [$k] ["count"] = M ( "comment" )->where ( "topic_id='" . $value ['id'] . "'" )->count ();
		}
    	$qdata=M("questionnaires")->where("openid='".$openid."'")->select();
   		 foreach ( $qdata as $k => $value ) {
			$qdata [$k] ["count"] = M ( "questions" )->where ( "questionnaire_id='" . $value ['id'] . "'" )->count ();
		}
		
		$cdata=M("comment")->alias('c')->join("wpsk_topic t on t.id=c.topic_id")->field('c.author,c.addtime,c.value,c.headimg,t.title,t.context')->where("openid='".$openid."'")->select();
		foreach ($cdata as $key => $value){
		$cdata[$key]['context']= preg_replace("/<img.+?\/>/", "", $value['context']);
		}
    	$this->assign("tdata",$tdata);
    	$this->assign("qdata",$qdata);
    	$this->assign("cdata",$cdata);
    	$this->assign("id",$id);
    	$this->display();
    
    }
    
    /**
     * 优惠券
     */
    public function coupon(){
    	$openid=$_SESSION['user']['openid'];
    	$wdata=M("coupon")->where("openid='".$openid."' and isused=0")->select();
    	$udata=M("coupon")->where("openid='".$openid."' and isused=1")->select();
    	$this->assign("wdata",$wdata);
    	$this->assign("udata",$udata);
    	//var_dump($wdata);
    	$this->display();
    	
    }
    
    /**
     * 个人资料
     */
    public function personaldata(){
    	$model=M("person");
    	if(!IS_POST){
    	$data=$_SESSION["user"];
    	$data["sex"]=$data["sex"]=="1"?"男":"女";
    	$temp=$model->where("openid='".$_SESSION["user"]['openid']."'")->find();
    	$data["xq"]=$temp['xq'];
    	$data['gx']=$temp['gx'];
    	$this->assign("info",$data);
    	
    	$this->display();
    	}
    	else{
    	
    	$alldata = array_merge ( $_POST, session ( 'user' ) ); //合并上用户信息
    	if($model->where("openid='".$_SESSION["user"]['openid']."'")->count()){
    	$state=$model->save($alldata);
    	}
    	else{
    	$state=$model->add($alldata);
    	}
    	 if ($state === false) {
				$msg = array ('status' => 0, 'msg' => "保存失败" );
			} 
			else {
				$msg = array ('status' => 1, 'msg' => "保存成功" );
			
			}
			$this->ajaxReturn ( $msg, 'JSON' );
    	}
    	
    }
    
    
 /**
	 * 上传
	 * @param unknown_type $filename
	 * @return string
	 */
	public function upload($filename) {
		$upload = new \Think\Upload (); // 实例化上传类
		$upload->maxSize = 3145728; // 设置附件上传大小
		$upload->exts = array ('jpg', 'gif', 'png', 'jpeg' ); // 设置附件上传类型
		$upload->rootPath = './Public/Upload/'; // 设置附件上传根目录
		$upload->savePath = '';
		// 上传单个文件 
		$info = $upload->uploadOne ( $filename );
		if (! $info) { // 上传错误提示错误信息
			$this->error ( $upload->getError () );
			exit ();
		} else { // 上传成功 获取上传文件信息
			return $info ['savepath'] . $info ['savename'];
		}
	}
	
	/**
     * 问卷详情分析
     */
    public function statistic()
    {

        /* 问卷概览信息 */
    	
        $qnID = I('get.questionnaireID/d');
        $questionnaire = M('Questionnaires')->field('id,type,name,description')->find($qnID);
        $type = $questionnaire['type'];

        if( $type == 'exam' ){
            $scores = M('Reply')->where("questionnaire_id=$qnID")->getField('total_score', true);

            sort($scores);
            $scoreNum = count($scores);
            $questionnaire['average'] = round(array_sum($scores)/$scoreNum, 1);
            $questionnaire['max_score'] = $scores[$scoreNum - 1];
            $questionnaire['min_score'] = $scores[0];
            $questionnaire['max_nicknames'] = implode(',', M('Reply')->where("questionnaire_id=$qnID and total_score=$questionnaire[max_score]")->getField('nickname', true) );
            $questionnaire['min_nicknames'] = implode(',', M('Reply')->where("questionnaire_id=$qnID and total_score=$questionnaire[min_score]")->getField('nickname', true) );
        }

        /* 读出指定问卷的所有问题 */
        $questions = M('Questions')->alias('qt')
                                   ->join('left join wpsk_questionnaires qn on qt.questionnaire_id=qn.id')
                                   ->where("qt.questionnaire_id=$qnID")
                                   ->getField('qt.id,qn.type questionnaire_type,qt.name,qt.options,qt.standard');

        /* 解析每个问题的选项 */
        $mapper = function ($item) {
            $item['options'] = json_decode($item['options'], true);

            if( $item['questionnaire_type'] == 'exam' )
            {
                $item['rate'] = 0;
                $item['rightCnt'] = 0;
                $item['falseCnt'] = 0;
            }

            return $item;
        };
        $questions = array_map($mapper, $questions);

        /* 开始计算每道题的准确率和统计每道题的每个选项的勾选情况 */
        $replys = M('Reply')->where("questionnaire_id=$qnID")->getField('reply', true);

        foreach ($replys as $reply) {
            $reply = json_decode($reply, true); //一套卷子的回答

            foreach ($reply as $questionID => $answer) { //$answer -- 卷子内一个问题的回答
                /* 针对考试卷累计正误 */
              
                if( preg_match('/^%u/', $answer) ){ //case: 简答题,  收集回答的前10个宽字符
                    $answer = unicodeDecode($answer);
                    $tag = mb_substr($answer, 0, 10, 'UTF-8');
                    $tag .= (mb_strlen($answer, 'UTF-8') > 10)? "...;\n\n" : ";\n\n";
                    $questions[$questionID]['options'][0]['replyList'][] = "\n".$tag; //收集简答题回答的一个摘要, 简答题只有一个选项且键为0
                }else{ //case: 勾选题, 统计勾选情况
                    $chooseList = explode(',', $answer);
                    foreach ($chooseList as $choose) {
                        $chooseInfo = explode(':', $choose);
                        $optionIndex = $chooseInfo[0];
                        $optionOthertext = isset($chooseInfo[1]) ? $chooseInfo[1] : null;

                        if( !isset($questions[$questionID]['options'][$optionIndex]['count']) ){
                            $questions[$questionID]['options'][$optionIndex]['count'] = 0;
                        }
                        $questions[$questionID]['options'][$optionIndex]['count']++; //累计勾选次数
                        if( isset($optionOthertext) ){ //case: 勾选题型里面的其它问题,  收集回答的前10个宽字符
                            $answer = unicodeDecode($optionOthertext);
                            $tag = mb_substr($answer, 0, 10, 'UTF-8');
                            $tag .= (mb_strlen($answer, 'UTF-8') > 10)? "...;\n\n" : ";\n\n";
                            $questions[$questionID]['options'][$optionIndex]['replyList'][] = "\n".$tag; //收集回答摘要
                        }
                    }
                }

            }

        }

      
		 $count = M('Reply')->where("questionnaire_id=$qnID")->count();
		 $this->assign("count",$count);
        $this->assign('questionnaire', $questionnaire);
        $this->assign('questions', $questions);
		
        $this->display();
    }
	
}